package com.taotao.Earthquake;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;

public class EarthquakeListFragment extends ListFragment {
    private static final String TAG = "Earthquake";
    private Handler handler = new Handler();
    ArrayAdapter<Quake> aa;
    ArrayList<Quake> earthquakes = new ArrayList<Quake>();

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        aa = new ArrayAdapter<Quake>(getActivity(), android.R.layout.simple_list_item_1, earthquakes);
        setListAdapter(aa);

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                refreshEarthquakes();
            }
        });
        t.start();
    }

    public void refreshEarthquakes() {
        try {
            InputStream in = readEarthquakeDataFromInternet();
            if (in == null) {
                Log.e(TAG, "readEarthquakeDataFromFile");
                in = readEarthquakeDataFromFile();
            }
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document dom = db.parse(in);
            Element docEle = dom.getDocumentElement();
            earthquakes.clear();

            NodeList nl = docEle.getElementsByTagName("entry");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {
                    Element entry = (Element)nl.item(i);
                    Element title = (Element)entry.getElementsByTagName("title").item(0);
                    Element g = (Element)entry.getElementsByTagName("georss:point").item(0);
                    Element when = (Element)entry.getElementsByTagName("updated").item(0);
                    Element link = (Element)entry.getElementsByTagName("link").item(0);

                    String details = title.getFirstChild().getNodeValue();
                    String linkString = link.getAttribute("href");

                    String dt = when.getFirstChild().getNodeValue();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'z'");
                    Date qdate = new GregorianCalendar(0,0,0).getTime();
                    try {
                        qdate = sdf.parse(dt);
                    } catch (ParseException e) {
                        Log.d(TAG, "Date parsing exception.", e);
                    }

                    Location l = new Location("dummyGPS");
                    if (g != null) {
                        String point = g.getFirstChild().getNodeValue();
                        String[] location = point.split(" ");
                        l.setLatitude(Double.parseDouble(location[0]));
                        l.setLongitude(Double.parseDouble(location[1]));
                    }

                    String magnitudeString = details.split(" ")[1];
                    int end = magnitudeString.length() - 1;
                    double magnitude = 0;
                    try {
                        magnitude = Double.parseDouble(magnitudeString.substring(0, end));
                        details = details.split(",")[1].trim();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    final Quake quake = new Quake(qdate, details, linkString, l, magnitude);
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            addNewQuake(quake);
                        }
                    });
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    private void addNewQuake(Quake quake) {
        earthquakes.add(quake);
        aa.notifyDataSetChanged();
    }

    private InputStream readEarthquakeDataFromFile()
    {
        InputStream inStream = null;
        try {
            inStream = getActivity().getAssets().open("USGS_Earthquake_1M2_5.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inStream;
    }

    private InputStream readEarthquakeDataFromInternet() {
        URL url;
        try {
            url = new URL(getString(R.string.quake_feed));
            URLConnection connection = url.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                return httpURLConnection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
